package com.example.cdctest.service.impl;
import com.example.cdctest.mapper.*;
import com.example.cdctest.pojo.*;
import com.example.cdctest.service.UserInfoService;
import com.example.cdctest.util.MyException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("userInfoService")
@Transactional(rollbackFor = Exception.class)
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private TestPaperMapper testPaperMapper;

    @Resource
    private ParticipantsMapper participantsMapper;

    @Resource
    private PostMapper postMapper;

    @Resource
    private EducationMapper educationMapper;

    @Override
    public void insert(UserInfo object) {
        userInfoMapper.insert(object);
    }

    @Override
    public void delete(Integer id) {

    }

    @Override
    public void delete(String ids) {

    }

    @Override
    public void update(UserInfo object) {
        userInfoMapper.updateUserPass(object);
    }

    @Override
    public UserInfo findById(Integer id) {
        return null;
    }

    @Override
    public List<UserInfo> findAll() {
        return null;
    }

    @Override
    public PageInfo<UserInfo> findPage(int pageSize) {
        return null;
    }

    @Override
    public UserInfo login(UserInfo userInfo) {
        return userInfoMapper.login(userInfo);
    }

    @Override
    public UserInfo isEmail(UserInfo userInfo) {
        return userInfoMapper.isEmail(userInfo);
    }

    @Override
    public UserInfo selectUserByEmail(String email) {
        return userInfoMapper.selectUserByEmail(email);
    }

    @Override
    public void updateUserInfo(UserInfo userInfo) {
        userInfoMapper.updateByEmail(userInfo);
    }

    //通过搜索条件，查出搜索到的数据(用户状态，起始日期，截止日期，搜索用户的条件，点击的页码)
    @Override
    public PageInfo<UserInfo> findAllUserInfo(Integer tai, Date logmin, Date logmax, String text, Integer pageNum, Integer pageSize) {
        //一页显示多少条
        PageHelper.startPage(pageNum,pageSize);
        List<UserInfo> userInfos=userInfoMapper.selectAllUserInfo(tai,logmin,logmax,text);
        //默认导航页码是8,可以通过参数设置
        PageInfo<UserInfo> pageInfo=new PageInfo<>(userInfos,10);
        return pageInfo;
    }

    //通过搜索条件，查出搜索到的数据的条数(用户状态，起始日期，截止日期，搜索用户的条件，点击的页码)
    @Override
    public Integer getUserInfoCount(Integer tai, Date logmin, Date logmax, String text, Integer pageNum, Integer pageSize) {
        //一页显示多少条
        PageHelper.startPage(pageNum,pageSize);
        Integer userInfoCount=userInfoMapper.selectUserInfoCount(tai,logmin,logmax,text);
        return userInfoCount;
    }

    //审核用户
    @Override
    public void updateUserStatus(Integer id, Integer userState) {
        userInfoMapper.updateUserStatus(id,userState);
    }

    //禁用或者启用用户
    @Override
    public void updateUser(Integer id) {
        userInfoMapper.updateUser(id);
    }

    //根据用户的id,获取用户的所有考试信息
    @Override
    public List<TestPaper> selectUserTestPapers(Integer userId) {

        return testPaperMapper.selectUserTestPaper(userId);
    }

    //根据用户的id,获取用户的所有考试信息数量
    @Override
    public Integer getUserTestPaperCount(Integer userId) {
        return testPaperMapper.selectUserTestPaperCount(userId);
    }

    //从excel表格中批量导入数据
    @Override
    public Boolean userInfoExcel(String fileName, MultipartFile file) throws Exception {
        boolean notNull=false;
        List<UserInfo> userInfoList=new ArrayList<>();
        if(!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")){
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003=true;
        if(!fileName.matches("^.\\.(?i)(xlsx)$")){
            isExcel2003=false;
        }
        //得到上传的表格
        Workbook wb=WorkbookFactory.create(file.getInputStream());
        Sheet sheet=wb.getSheetAt(0);
        if(sheet!=null){
            notNull=true;
        }
        UserInfo userInfo;
        //获得表总行数
        int num = sheet.getLastRowNum();
        //获得表总列数
        int col=sheet.getRow(0).getLastCellNum();
        for (int r = 1; r <=num; r++) {
            Row row=sheet.getRow(r);
            if(row==null){
                continue;
            }
            userInfo=new UserInfo();
            String email=row.getCell(0).getStringCellValue();
            if(email==null||email.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,邮箱未填写");
            }
            row.getCell(1).setCellType(CellType.STRING);
            String password=row.getCell(1).getStringCellValue();
            if(password==null||password.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,密码未填写");
            }
            String sex=row.getCell(2).getStringCellValue();
            if(sex==null||sex.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,性别未填写");
            }
            String area=row.getCell(3).getStringCellValue();
            if(area==null||area.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,地址未填写");
            }
            String userName=row.getCell(4).getStringCellValue();
            if(userName==null||userName.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,姓名未填写");
            }
            row.getCell(5).setCellType(CellType.STRING);
            String dates=row.getCell(5).getStringCellValue();
            if(dates==null||dates.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,出生日期未填写");
            }
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            //将单元格中获得的String类型转化为double类型
            Double d=Double.parseDouble(dates);
            //再将double类型通过HSSFDateUtil类将其转化为Date类型
            Date date= HSSFDateUtil.getJavaDate(d);
            sdf.format(date);
            row.getCell(6).setCellType(CellType.STRING);
            String educationId=row.getCell(6).getStringCellValue();
            if(educationId==null||educationId.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,学历Id未填写");
            }
            row.getCell(7).setCellType(CellType.STRING);
            String postId=row.getCell(7).getStringCellValue();
            if(postId==null||postId.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,岗位id未填写");
            }
            row.getCell(8).setCellType(CellType.STRING);
            String phone=row.getCell(8).getStringCellValue();
            if(phone==null||phone.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,手机号未填写");
            }
            row.getCell(9).setCellType(CellType.STRING);
            String vipUser=row.getCell(9).getStringCellValue();
            if(vipUser==null||vipUser.isEmpty()){
                throw new Exception("导入失败(第\"+(r+1)+\"行,内普未填写");
            }

            userInfo.setEmail(email);
            userInfo.setPassword(password);
            userInfo.setSex(sex);
            userInfo.setArea(area);
            userInfo.setUserName(userName);
            userInfo.setBirthday(date);

            Education education=new Education();
            education.setId(Integer.parseInt(educationId));
            userInfo.setEducation(education);

            Post post=new Post();
            post.setId(Integer.parseInt(postId));
            userInfo.setPost(post);

            userInfo.setPhone(phone);
            userInfo.setVipUser(Integer.parseInt(vipUser));

            userInfoList.add(userInfo);
        }

        for (UserInfo user:userInfoList
             ) {
            String email=user.getEmail();
            UserInfo temp=userInfoMapper.selectUserByEmail(email);
            if(temp==null){
                userInfoMapper.insertSelective(user);
            }else{
                userInfoMapper.updateByPrimaryKeySelective(user);
            }
        }
        return notNull;
    }

    //取出所有的内测用户
    @Override
    public List<UserInfo> selectFormalUser() {
        return userInfoMapper.selectFormalUser();
    }

    //根据选中的用户Id,以及考试信息,添加考核人员
    @Override
    public void insertSelectUser(String[] ids, Integer examinationId) {
        UserInfo userInfo=null;
        Examination examination=null;
        for (String id : ids) {
            Participants participants=new Participants();
            userInfo=new UserInfo();
            userInfo.setId(Integer.parseInt(id));
            participants.setUserInfo(userInfo);
            examination=new Examination();
            examination.setId(examinationId);
            participants.setExamination(examination);

            //得到考试参与人信息,到数据库查询
           Participants participantsUsers=participantsMapper.selectParticipant(participants);
            if(participantsUsers!=null){    //如果存在，更新信息
                participants.setId(participantsUsers.getId());
                System.out.println(participants.toString());
                participantsMapper.updateParticipants(participants);
            }else{//如果不存在，插入信息
                participantsMapper.insertSelectUser(participants);
            }
        }
    }

    //从数据库取出岗位信息,并转到岗位管理界面
    @Override
    @Cacheable(value = "questionTypeCache",key = "'getAllPost'")
    public List<Post> findAllPost() {
        return postMapper.selectAllPost();
    }

    //从数据库取出学历信息,并转到学历管理界面
    @Override
    @Cacheable(value = "questionTypeCache",key = "'getAllEducation'")
    public List<Education> findAllEducation() {
        return educationMapper.selectAllEducation();
    }

    //添加岗位信息
    @Override
    public Integer addPost(Post post) {
        return postMapper.insert(post);
    }

    //修改岗位的状态信息
    @Override
    public void updatePostEnable(Integer id) {
        postMapper.updatePostEnable(id);
    }

    //修改岗位排序
    @Override
    public void updatePostSort(Post post) {
        postMapper.updatePostSort(post);
    }

    //添加学历信息
    @Override
    public Integer addEducation(Education education) {
        return educationMapper.insert(education);
    }

    //修改学历的状态信息
    @Override
    public void updateEducationEnable(Integer id) {
        educationMapper.updateEducationEnable(id);
    }

    //修改学历排序
    @Override
    public void updateEducationSort(Education education) {
        educationMapper.updateEducationSort(education);
    }

    //申请为内测用户
    @Override
    public void updateVipUser(Integer id) {
        userInfoMapper.updateVipUser(id);
    }
}
